import 'dart:convert';

import 'package:homepad/logger/logger.dart';
import 'package:http/http.dart' as http;

class WeatherInfo {
  final String province;
  final String city;
  final String weather;
  final String temperature;
  final String reportTime;

  WeatherInfo({
    required this.province,
    required this.city,
    required this.weather,
    required this.temperature,
    required this.reportTime,
  });

  factory WeatherInfo.fromJson(Map<String, dynamic> json) {
    return switch (json) {
      {
        "province": String province,
        "city": String city,
        "weather": String weather,
        "temperature": String temperature,
        "reporttime": String reportTime,
      } =>
        WeatherInfo(
          province: province,
          city: city,
          weather: weather,
          temperature: temperature,
          reportTime: reportTime,
        ),
      _ => throw const FormatException("failed to load weatherInfo"),
    };
  }

  @override
  String toString() {
    return "$reportTime $city: $weather -> $temperature";
  }
}

Future<WeatherInfo?> fetchWeatherInfo(String city, String key) async {
  final uri = Uri(
      scheme: "https",
      host: "restapi.amap.com",
      path: "/v3/weather/weatherInfo",
      queryParameters: {"extension": "base", "city": city, "key": key});

  var client = http.Client();
  try {
    final response = await client.get(uri);
    if (response.statusCode != 200) {
      logger.error("status.code=${response.statusCode}");
      return null;
    }

    final responseJson = jsonDecode(response.body) as Map<String, dynamic>;
    var live = (responseJson["lives"] as List<dynamic>?)?.first;
    if (live == null) {
      return null;
    }

    final info = WeatherInfo.fromJson(live as Map<String, dynamic>);
    return info;
  } catch (e) {
    logger.error(e.toString());
  } finally {
    client.close();
  }
  return null;
}

void main(List<String> arguments) async {
  logger.info("Ok,let's go!");

  const city = "440306";
  const key = "67d9dcd06a58176297925c84a2427cca";

  final info = await fetchWeatherInfo(city, key);
  if (info == null) return;
  logger.info(info);
}
